package com.benefm.multipar.pad.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.widget.GridLayout;

import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;

import com.benefm.multipar.pad.AppConfig;
import com.benefm.multipar.pad.MqttManager;
import com.benefm.multipar.pad.R;
import com.benefm.multipar.pad.databinding.ActivityMainBinding;
import com.benefm.multipar.pad.event.BloodPressureEvent;
import com.benefm.multipar.pad.event.EventAction;
import com.benefm.multipar.pad.event.GyroscopeInfoEvent;
import com.benefm.multipar.pad.event.MsgEvent;
import com.benefm.multipar.pad.http.HttpRequest;
import com.benefm.multipar.pad.http.HttpResult;
import com.benefm.multipar.pad.model.HomeResult;
import com.benefm.multipar.pad.model.PersonInfo;
import com.benefm.multipar.pad.util.ACache;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends BaseActivity {

    protected ActivityMainBinding binding;

    protected static final int MARGIN = 10;

    protected final int COUNT = 4 * 3;

    protected int pageIndex = 1;

    protected boolean refresh = false;

    protected List<PersonInfo> personList = new ArrayList<>();

    protected List<MqttManager> managerList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        EventBus.getDefault().register(this);
        initData();

        binding.refreshLayout.setEnableRefresh(true);
        binding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            refresh = true;
            getDevices(false, pageIndex);
        });

        binding.leftImage.setOnClickListener(v -> {
            pageIndex--;
            getDevices(true, pageIndex);
        });

        binding.rightImage.setOnClickListener(v -> {
            pageIndex++;
            getDevices(true, pageIndex);
        });

        getDevices(true, pageIndex);

    }


    private void initData() {
        for (int i = 0; i < COUNT; i++) {
            HomeItemView itemView = new HomeItemView(this);
            GridLayout.LayoutParams params = new GridLayout.LayoutParams();
            params.width = 0; // 宽度自适应
            params.height = 0; // 高度自适应
            params.setMargins(MARGIN, MARGIN, MARGIN, MARGIN);
            params.columnSpec = GridLayout.spec(i % 3, 1f); // 列权重均分
            params.rowSpec = GridLayout.spec(i / 3, 1f);    // 行权重均分
            itemView.setOnClickListener();
            binding.gridLayout.addView(itemView, params);
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(MsgEvent event) {
        if (refresh)
            return;
        if (EventAction.ECG_DATA_LEAD_II == event.getAction()) {
            String userId = event.getTag();
            List<Short> list = (List<Short>) event.getT();
            for (int i = 0; i < COUNT; i++) {
                HomeItemView itemView = (HomeItemView) binding.gridLayout.getChildAt(i);
                if (itemView != null && itemView.getTag().equals(userId)) {
                    itemView.updateWave(list);
                    break;
                }
            }
        } else if (EventAction.DEVICE_ECG_HR == event.getAction()) {
            int hr = (int) event.getT();
            String userId = event.getTag();
            updateInfo(hr, 1, userId);
        } else if (EventAction.DEVICE_BLOOD_PRESSURE == event.getAction()) {
            BloodPressureEvent bpEvent = (BloodPressureEvent) event.getT();
            String userId = event.getTag();
            for (int i = 0; i < COUNT; i++) {
                HomeItemView itemView = (HomeItemView) binding.gridLayout.getChildAt(i);
                if (itemView != null && itemView.getTag().equals(userId)) {
                    itemView.updateBpData(bpEvent);
                    break;
                }
            }
        } else if (EventAction.DEVICE_SPO2 == event.getAction()) {
            int spo2 = (int) event.getT();
            String userId = event.getTag();
            updateInfo(spo2, 2, userId);
        } else if (EventAction.DEVICE_GYROSCOPE == event.getAction()) {
            GyroscopeInfoEvent infoEvent = (GyroscopeInfoEvent) event.getT();
            String userId = event.getTag();
            for (int i = 0; i < COUNT; i++) {
                HomeItemView itemView = (HomeItemView) binding.gridLayout.getChildAt(i);
                if (itemView != null && itemView.getTag().equals(userId)) {
                    itemView.updateGyroscopeInfo(infoEvent);
                    break;
                }
            }
        } else if (EventAction.DEVICE_BATTERY == event.getAction()) {
            int voltage = (int) event.getT();
            String userId = event.getTag();
            for (int i = 0; i < COUNT; i++) {
                HomeItemView itemView = (HomeItemView) binding.gridLayout.getChildAt(i);
                if (itemView != null && itemView.getTag().equals(userId)) {
                    itemView.updateBattery(voltage);
                    break;
                }
            }
        }
    }

    private void updateInfo(int value, int type, String userId) {
        for (int i = 0; i < COUNT; i++) {
            HomeItemView itemView = (HomeItemView) binding.gridLayout.getChildAt(i);
            if (itemView != null && itemView.getTag().equals(userId)) {
                itemView.updateInfo(type, String.valueOf(value));
                break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消所有订阅
        for (MqttManager manager : managerList) {
            if (manager != null) {
                manager.unsubscribeTopic();
                manager.disconnect();
            }
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setMessage("是否需要退出登录？")
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                .setPositiveButton("确定", (dialog, which) -> {
                    dialog.dismiss();
                    ACache.get(this).remove(AppConfig.LOGIN_INFO);
                    MainActivity.this.finish();
                    startActivity(new Intent(this, LoginActivity.class));
                })
                .create()
                .show();
    }

    //将用户显示在屏幕上 并订阅用户的数据
    private void displayInfoOnScreen(int total) {
        binding.leftImage.setVisibility(pageIndex == 1 ? View.INVISIBLE : View.VISIBLE);
        binding.rightImage.setVisibility(total <= COUNT * pageIndex ? View.INVISIBLE : View.VISIBLE);
        //先重置所有itemView
        for (int i = 0; i < COUNT; i++) {
            HomeItemView itemView = (HomeItemView) binding.gridLayout.getChildAt(i);
            if (itemView != null)
                itemView.resetView();
        }
        for (MqttManager m : managerList) {
            if (m.isConnect())
                m.disconnect();
        }
        managerList.clear();

        subscribeItems();

    }

    private void subscribeItems() {
        for (int i = 0; i < personList.size(); i++) {
            PersonInfo info = personList.get(i);
            HomeItemView itemView = (HomeItemView) binding.gridLayout.getChildAt(i);
            if (itemView != null) {
                itemView.setInfo(info);
                itemView.setTag(info.userId);
            }
            System.out.println(info.deviceMac);
            //mac地址不为空 并且在线的
            if (!TextUtils.isEmpty(info.deviceMac)) {
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    MqttManager manager = new MqttManager(info.deviceMac);
                    manager.initMqtt();
                    managerList.add(manager);
                }, 200);
            }
        }

    }

    private void getDevices(boolean show, int page) {
        if (show)
            showLoading();
        HttpRequest.getDevices(page, COUNT, new Callback<HttpResult<HomeResult>>() {
            @Override
            public void onResponse(Call<HttpResult<HomeResult>> call, Response<HttpResult<HomeResult>> response) {
                new Handler(Looper.getMainLooper()).postDelayed(() -> refresh = false, 1000);
                hideLoading();
                binding.refreshLayout.finishRefresh();
                if (response.body() != null && response.isSuccessful()) {
                    HomeResult homeResult = response.body().resultData;
                    int total = homeResult.total;
                    List<PersonInfo> list = homeResult.datas;
                    if (list != null) {
                        personList.clear();
                        personList.addAll(list);
                        displayInfoOnScreen(total);
                    }
                }
            }

            @Override
            public void onFailure(Call<HttpResult<HomeResult>> call, Throwable t) {
                t.printStackTrace();
                hideLoading();
                binding.refreshLayout.finishRefresh();
            }
        });
    }

}